﻿namespace LS.Nc6.Web.Entry
{
    public static class RequestHelper
    {
        public const char Newline = '\n';//换行
        public const string ReturnAndNewline = "\r\n";//回车换行

        /// <summary>
        /// 检查危险字符
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public static string FilterParam(string sInput)
        {
            if (sInput == null || sInput == "")
                return null;
            string sInput1 = sInput.ToLower();
            string output = sInput;
            //string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
            //if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
            //{
            //    throw new Exception("字符串中含有非法字符!");
            //}
            //else
            //{
            output = output.Replace("'", "''");
            //}
            return output;
        }

        public static T? GetValueOrNull<T>(this string valueAsString) where T : struct
        {
            if (string.IsNullOrEmpty(valueAsString))
                return null;
            return (T)Convert.ChangeType(valueAsString, typeof(T));
        }

        public static T GetQueryValueOrNull<T>(this string valueAsString, T defaultValue = default(T))
        {
            if (string.IsNullOrEmpty(valueAsString))
                return defaultValue;
            return (T)Convert.ChangeType(valueAsString, typeof(T));
        }

        public static T GetValueOrDefault<T>(object val, T defaultValue = default(T))
        {
            if (val == null)
                return defaultValue;
            return (T)Convert.ChangeType(val, typeof(T));
        }
        /// <summary>
        /// 格式化获取日期
        /// </summary>
        /// <param name="dateStr"></param>
        /// <returns></returns>
        public static List<string> GetDateForStr(string dateStr)
        {
            List<string> datels = new List<string>();
            var matchcoll = System.Text.RegularExpressions.Regex.Matches(dateStr, @"\d{4}-\d{2}-\d{2}");
            foreach (var item in matchcoll)
            {
                datels.Add(item.ToString());
            }
            return datels;
        }
      
        public static string RemoveSuffixChar(string str)
        {
            return System.Text.RegularExpressions.Regex.Replace(str, ",$", "");
        }


        /// <summary>
        /// 根据文件流读取json
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static JsonNode GetInputStream(Stream stream)
        {
            string json = string.Empty;
            if (stream.Length != 0)
            {
                StreamReader sr = new StreamReader(stream,Encoding.UTF8);
                json = sr.ReadToEnd();
            }
            return string.IsNullOrEmpty(json) ? null : JsonNode.Parse(json);
        }


        public static List<string> GetStringListByReturnAndNewline(string collection)
        {
            var list = new List<string>();
            if (string.IsNullOrEmpty(collection)) return list;

            var array = collection.Split(Newline);
            list.AddRange(from item in array where !string.IsNullOrEmpty(item) select item.Trim());

            return list;
        }
        public static bool Contains<T>(IEnumerable<T> list, T value)
        {
            return list != null && list.Contains(value);
        }

        public static int GetStartCount(char startChar, string content)
        {
            if (content == null)
            {
                return 0;
            }
            var count = 0;

            foreach (var theChar in content)
            {
                if (theChar == startChar)
                {
                    count++;
                }
                else
                {
                    break;
                }
            }
            return count;
        }

        /// <summary>
        ///  获取request body  返回string类型
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public static string GetBody(this HttpRequest Request)
        {
            string result = string.Empty;
            try
            {
                Request.EnableBuffering();
                using (Stream stream = Request.Body)
                {
                    byte[] buffer = new byte[Request.ContentLength.Value];
                    stream.Read(buffer, 0, buffer.Length);
                    result = Encoding.UTF8.GetString(buffer);
                    Request.Body.Seek(0, SeekOrigin.Begin);
                }
            }
            catch (Exception) { }
            return result;
        }

        /// <summary>
        /// 获取request body 并转换Model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Request"></param>
        /// <returns></returns>
        public static T BodyModel<T>(this HttpRequest Request) where T : new()
        {
            T t = new T();

            try
            {
                Request.EnableBuffering();
                using (Stream stream = Request.Body)
                {
                    byte[] buffer = new byte[Request.ContentLength.Value];
                    stream.Read(buffer, 0, buffer.Length);
                    string content = Encoding.UTF8.GetString(buffer);
               
                    Request.Body.Seek(0, SeekOrigin.Begin);
                    t = JsonSerializer.Deserialize<T>(content, CommonMethodHelper.MyJsonOptions);
                }
            }
            catch (Exception)
            {
                t = default;
            }
            return t;
        }

       
    }
}
